package com.ruoyi.netty.connection;

import com.ruoyi.netty.metrics.MetricsService;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * PLC连接管理器
 * 管理所有连接的PLC设备
 */
@Component
@Slf4j
public class ConnectionManager {
    
    private final Map<String, Channel> connections = new ConcurrentHashMap<>();
    
    @Autowired(required = false)
    private MetricsService metricsService;
    
    /**
     * 添加新连接
     */
    public void addConnection(Channel channel) {
        String id = getChannelId(channel);
        connections.put(id, channel);
        log.info("Added connection: {}, total: {}", id, connections.size());
        
        if (metricsService != null) {
            metricsService.incrementActiveConnections();
        }
    }
    
    /**
     * 移除连接
     */
    public void removeConnection(Channel channel) {
        String id = getChannelId(channel);
        connections.remove(id);
        log.info("Removed connection: {}, total: {}", id, connections.size());
        
        if (metricsService != null) {
            metricsService.decrementActiveConnections();
        }
    }
    
    /**
     * 获取连接数量
     */
    public int getConnectionCount() {
        return connections.size();
    }
    
    /**
     * 检查连接是否存在
     */
    public boolean hasConnection(String id) {
        return connections.containsKey(id);
    }
    
    /**
     * 获取连接ID
     */
    private String getChannelId(Channel channel) {
        InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
        return address.getHostString() + ":" + address.getPort();
    }
} 